package com.framework.boc.statistics.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.framework.boc.statistics.entity.StatisticalBatch;
import com.framework.boc.statistics.entity.StatisticalRecord;
import com.framework.boc.statistics.entity.Template;
import com.framework.boc.statistics.mapper.StatisticalRecordMapper;
import com.framework.boc.statistics.properties.ElephantGlobalConfig;
import com.framework.boc.statistics.service.IStatisticalRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 统计记录表 服务实现类
 * </p>
 *
 * @author Leil
 * @since 2020-12-23
 */
@Service
public class StatisticalRecordServiceImpl extends ServiceImpl<StatisticalRecordMapper, StatisticalRecord> implements IStatisticalRecordService {

    @Autowired
    StatisticalBatchServiceImpl statisticalBatchService;

    @Autowired
    TemplateServiceImpl templateService;


    /**
     * 获取记录
     * @param batchId       批次ID
     * @return              记录列表
     */
    public List<JSONObject> getRecords(Integer batchId) {
        List<StatisticalRecord> list = this.list(Wrappers.<StatisticalRecord>lambdaQuery()
                .eq(StatisticalRecord::getBatchId, batchId));
        List<JSONObject> records = list.stream().map(item -> {
            JSONObject record = JSONObject.parseObject(item.getJsonText());
            record.put("id", item.getId());
            return record;
        }).collect(Collectors.toList());
        return records;
    }

    /**
     * 导出数据
     * @param batchId       批次ID
     * @param templateId    对应模板ID
     * @return              导出结果
     */
    public String exportRecords(Integer batchId, Integer templateId) {
        StatisticalBatch batch = this.statisticalBatchService.getById(batchId);
        Template template = this.templateService.getById(templateId);
        List<StatisticalRecord> list = this.list(
                Wrappers.<StatisticalRecord>lambdaQuery()
                        .eq(StatisticalRecord::getBatchId, batchId));
        List<JSONObject> records = list.stream().map(record -> {
            String jsonText = record.getJsonText();
            JSONObject jsonObject = JSONObject.parseObject(jsonText);
            return jsonObject;
        }).collect(Collectors.toList());

        String fileName = ElephantGlobalConfig.getProfile() + ElephantGlobalConfig.getExportFileSwap() + "/" + batch.getBatchTitle() +".xlsx";

        EasyExcel.write(fileName).withTemplate(template.getPath()).sheet().doFill(records);
        return fileName;
    }
}
